<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="status" slot-scope="scope">
        <el-switch
          v-model="scope.row.status"
          active-text="运行"
          :active-value="0"
          inactive-text="暂停"
          :inactive-value="1"
          @change="statusChange(scope.row.jobId, scope.row.status)">
        </el-switch>
      </template>
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.schedule_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button v-if="permission.schedule_edit" size="small" type="text" icon="el-icon-cpu" @click.native="rowRun(scope.row)">立即执行</el-button>
        <el-button v-if="permission.schedule_edit" size="small" type="text" icon="el-icon-view" @click.native="rowViewLog(scope.row)">查看日志</el-button>
      </template>
    </avue-crud>

    <el-dialog title="任务日志" v-if="logBox" append-to-body :visible.sync="logBox" width="60%">
      <avue-crud :option="logOption"
                 :table-loading="logLoading"
                 :data="logData"
                 ref="logCrud"
                 :page.sync="logPage"
                 @current-change="logCurrentChange"
                 @size-change="logSizeChange"
                 @on-load="logOnLoad">
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, getLogList, getDetail, add, update, remove, pause, resume, run} from "@/api/system/schedule";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        data: [],
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          labelWidth: 100,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          align: "center",
          border: false,
          index: true,
          delBtn: false,
          viewBtn: false,
          selection: true,
          menuWidth: 240,
          dialogWidth: 500,
          dialogClickModal: false,
          column: [
            {
              label: "bean名称",
              prop: "beanName",
              row: true,
              span: 24,
              search: true,
              rules: [{
                required: true,
                message: "请输入bean名称",
                trigger: "blur"
              }],
              overHidden:true,
            },
            {
              label: "cron表达式",
              prop: "cronExpression",
              row: true,
              span: 24,
              rules: [{
                required: true,
                message: "请输入cron表达式",
                trigger: "blur"
              }],
              overHidden:true,
            },
            {
              label: "执行参数",
              prop: "params",
              row: true,
              span: 24,
              overHidden:true,
            },
            {
              label: "任务状态",
              prop: "status",
              type: "switch",
              value: 0,
              row: true,
              span: 24,
              slot: true,
              dicData: [
                {
                  label: "暂停",
                  value: 1
                },
                {
                  label: "正常",
                  value: 0
                }
              ],
            },
            {
              label: "任务备注",
              prop: "remark",
              row: true,
              span: 24,
              overHidden:true,
            },
            {
              label: "创建时间",
              prop: "createTime",
              width:'150',
              display: false,
            },
          ]
        },
        logData: [],
        logQuery: {},
        logBox: false,
        logLoading: false,
        logPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        logOption: {
          tip: false,
          searchShow: false,
          border: false,
          addBtn: false,
          delBtn: false,
          editBtn: false,
          menu: false,
          header: false,
          column: [
            {
              label: "bean名称",
              prop: "beanName",
              overHidden:true,
            },
            {
              label: "执行参数",
              prop: "params",
              overHidden:true,
            },
            {
              label: "执行状态",
              prop: "status",
              dicData: [
                {
                  label: "成功",
                  value: 0
                },
                {
                  label: "失败",
                  value: 1
                }
              ],
            },
            {
              label: "失败信息",
              prop: "error",
              overHidden:true,
            },
            {
              label: "耗时(毫秒)",
              prop: "times",
              overHidden:true,
            },
            {
              label: "执行时间",
              prop: "createTime",
              width:'150',
            },
          ]
        }
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.schedule_add, false),
          viewBtn: this.vaildData(this.permission.schedule_view, false),
          delBtn: this.vaildData(this.permission.schedule_delete, false),
          editBtn: this.vaildData(this.permission.schedule_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.jobId);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.jobId);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      rowRun(row) {
        this.$confirm("确定立即执行?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return run(row.jobId);
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "执行成功!"
            });
          });
      },
      rowViewLog(row) {
        this.logBox = true;
        this.logPage.currentPage = 1;
        this.logQuery.jobId = row.jobId;
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.jobId).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      statusChange(jobId, status){
        if(status === 1){
          pause(jobId).then(() => {
            this.$message({
              type: "success",
              message: "任务已暂停!"
            });
          }, error => {
            loading();
            console.log(error);
          });
        }else{
          resume(jobId).then(() => {
            this.$message({
              type: "success",
              message: "任务已运行!"
            });
          }, error => {
            loading();
            console.log(error);
          });
        }
      },
      logOnLoad(page, params = {}) {
        let values = {
          ...params,
          ...this.logQuery,
        };
        this.logLoading = true;
        getLogList(page.currentPage, page.pageSize, values).then(res => {
          const data = res.data.data;
          this.logPage.total = data.total;
          this.logData = data.records;
          this.logLoading = false;
        });
      },
      logCurrentChange(currentPage){
        this.logPage.currentPage = currentPage;
      },
      logSizeChange(pageSize){
        this.logPage.pageSize = pageSize;
      },
    }
  };
</script>

<style>
</style>
